package mythical.controller;

import cn.hutool.core.bean.BeanUtil;

import dto.UserLoginDto;
import dto.UserSaveDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import mythical.exceptions.DataBaseException;
import mythical.result.Result;
import mythical.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import po.User;
import vo.UserLoginVO;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;

    /**
     * 用户注册
     * @param userSaveDto
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserSaveDto userSaveDto){
        log.info("创建用户：{}",userSaveDto);
        User user = new User();
        BeanUtil.copyProperties(userSaveDto,user);
        user.setGrade(1);
        user.setLife(100);
        user.setStrength(100);
        user.setAgility(100);
        user.setPower(100);
        user.setSpirit(100);
        user.setMoney(0);
        user.setCreateTime(LocalDateTime.now());
        try {
            userService.save(user);
        } catch (Exception e) {
            throw new DataBaseException("已有用户注册！请更换用户名！");
        }
        return Result.success();
    }

    /**
     * 用户登录
     * @param userLoginDto
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDto userLoginDto){
        log.info("用户登录：{}",userLoginDto);
        UserLoginVO userLoginVO = userService.login(userLoginDto);
        return Result.success(userLoginVO);
    }

}
